package com.macro.mall.portal.util;
import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.dto.AddressData;
import com.macro.mall.portal.config.AddressConfing;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 地址智能识别
 */
@Slf4j
@Component
public class Recognition {
    @Autowired
    private AddressConfing api;
    public AddressData addr(String pant) {
        AddressData ums = null;

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + api.getAppcode());
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
//        "赵王17267365647浙江省秀洲区王江泾镇南元丰大道82282700"
        bodys.put("address", pant);

        try {
            HttpResponse response = HttpUtils.doPost(api.getHost(), api.getPath(), api.getMethod(),
                    headers, querys, bodys);
            System.out.println(response.toString());
            String string = EntityUtils.toString(response.getEntity());
            log.debug("api地址解析结果"+string);
            //json 解析
            JSONObject jsonObject = JSONObject.parseObject(string);
            if (jsonObject.getInteger("code") == 200) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (null!=data) {
                    ums = new AddressData();
                    ums.setCity(data.getString("city"));
                    ums.setProvince(data.getString("province"));
                    ums.setName(data.getString("name"));
                    ums.setPhoneNumber(data.getString("mobile"));
                    ums.setRegion(data.getString("area"));
                    ums.setDetailAddress(data.getString("detail"));
                    ums.setPostCode(data.getString("zipCode"));

                }
            }
            //获取response的body
            System.out.println("+++++++++++++++++++++++"+EntityUtils.toString(response.getEntity()));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ums;
    }

}
